package com.wx.resume_excel.listener;

import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.*;

import java.util.List;

/**
 * 文档中UserList中设置超链接的监听器对象
 *
 * @Auther 田艺鹏
 * @DateTime 2020-08-03 09:52
 */
public class HyperLinkHandler implements CellWriteHandler {
    @Override
    public void beforeCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Row row, Head head, Integer integer, Integer integer1, Boolean aBoolean) {

    }

    @Override
    public void afterCellCreate(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, Cell cell, Head head, Integer integer, Boolean aBoolean) {

    }

    /**
     * 数据填充完成后执行的方法
     * @param writeSheetHolder
     * @param writeTableHolder
     * @param list
     * @param cell
     * @param head
     * @param integer
     * @param aBoolean
     */
    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<CellData> list, Cell cell, Head head, Integer integer, Boolean aBoolean) {
        if(cell.getColumnIndex() >= 0 && cell.getRowIndex() > 0){
            if(cell.getStringCellValue() == null || "null".equals(cell.getStringCellValue())){
                cell.setCellValue("");
            }
        }
        if (cell.getRowIndex() > 0 && cell.getColumnIndex() == 0){
            //获取workbook 即文档对象
            Workbook workbook = cell.getSheet().getWorkbook();

            //创建单元格格式对象
            CellStyle cellStyle = workbook.createCellStyle();

            //创建单元格字体对象
            Font font = workbook.createFont();
            font.setFontHeightInPoints((short) 10);
            font.setColor(IndexedColors.BLUE.getIndex());
            font.setFontName("宋体");
            cellStyle.setFont(font);
            cell.setCellStyle(cellStyle);

            //获取单元格中的填充内容
            String stringCellValue = cell.getStringCellValue();
            CreationHelper helper=writeSheetHolder.getSheet().getWorkbook().getCreationHelper();
            Hyperlink hyperlink=helper.createHyperlink(HyperlinkType.DOCUMENT); //文档内引用地址
            //设置超链接地址 （根据具体的业务进行修）
            hyperlink.setAddress(cell.getRowIndex()+"."+stringCellValue+"!A1"); //超链接地址(sheet名+!A1)
            cell.setHyperlink(hyperlink);

        }
    }
}
